package nxt.mypackage;

import lejos.nxt.*;


import java.io.DataInputStream;
import java.io.IOException;

import lejos.nxt.Motor;
import lejos.nxt.Sound;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;

public class NXT {
	
	public static void main(String[] args) {
		try {
			NXT nxt = new NXT();
			nxt.run();
		} catch (Exception exc) {
			LCD.clear();
			LCD.drawString(exc.getMessage(), 0, 0);
			LCD.refresh();
		}
	}

	private void shutdown() {
			System.exit(0);
	}
	
	
	public void run() throws InterruptedException, IOException {
		
		//init();
		// add listener for ESCAPE button
		Button.ESCAPE.addButtonListener(new ButtonListener() {
			public void buttonReleased(Button arg0) {
				// ignore
			}
			public void buttonPressed(Button arg0) {
				// shutdown
				shutdown();
			}
		});
		// wait for sender connecting to brick
		display("please wait...");
		BTConnection connection = Bluetooth.waitForConnection();
		display("ready");
		Sound.buzz();
		// listen for incoming signals
		boolean stop = false; // presently, stop is never set to true
		while(!stop) {
			int received = listen(connection);
			display("received " + received);
			try {
				comunicate(NXTCom.values()[received]);
			} catch(ArrayIndexOutOfBoundsException e) {
				// ignore invalid signals
				display("invalid signal!");
			}
		}
	}

	private int listen(BTConnection connection) throws IOException,
			InterruptedException {
		DataInputStream input = connection.openDataInputStream();
		int signal = input.readInt();
		input.close();
		Thread.sleep(100); // wait for data to drain
		return signal;
	}

	private void comunicate(NXTCom signal) {
		Comunication nxtcom = new Comunication(signal);
		nxtcom.start();
	}

	private void forward() {
		Motor.A.forward();
		Motor.B.forward();
	}

	private void backward() {
		Motor.A.backward();
		Motor.B.backward();
	}

	private void left() {
		Motor.A.forward();
		Motor.B.backward();
	}

	private void right() {
		Motor.A.backward();
		Motor.B.forward();
	}

	private void stop() {
		Motor.A.stop();
		Motor.B.stop();
	}

	private void display(String message) {
		LCD.clear();
		LCD.drawString(message, 0, 0);
		LCD.refresh();
	}
	
	class Comunication extends Thread{
		private NXTCom nxtcom = NXTCom.PING;

		public Comunication(NXTCom nxtcom) {
			this.nxtcom = nxtcom;
		}

		public void run() {
			// signal?
			switch (nxtcom) {
			case TRRS: {
				forward();
				break;
			}
			case BUMP: {
				Sound.buzz();
				backward();
				break;
			}		
			}
		}		
	}
}
